<template>
  <div>
    <h1>领养管理</h1>
    <el-form :inline="true" :model="fromData" class="demo-form-inline">
      <el-form-item label="宠物姓名">
        <el-input v-model="fromData.name" placeholder="请输入宠物姓名"></el-input>
      </el-form-item>
      <el-form-item label="宠物类型">
        <el-select v-model="fromData.type" placeholder="宠物类型">
          <el-option label="狗" value="狗"></el-option>
          <el-option label="猫" value="猫"></el-option>
          <el-option label="其他" value="其他"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect">查询</el-button>
      </el-form-item>
          <el-button type="success" @click="showAddForm = true">添加宠物</el-button>
    </el-form>

    <!-- 添加宠物的弹出框 -->
    <!-- <el-button type="success" @click="showAddForm = true">添加宠物</el-button> -->
    <el-dialog title="添加宠物" :visible.sync="showAddForm" width="30%">
      <el-form :model="newPetForm" ref="newPetFormRef" :rules="rules">
        <el-form-item label="宠物姓名" prop="name">
          <el-input v-model="newPetForm.name"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型">
          <el-select v-model="newPetForm.type" placeholder="请选择宠物类型">
            <el-option label="狗" value="狗"></el-option>
            <el-option label="猫" value="猫"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物年龄" prop="age">
          <el-input-number v-model="newPetForm.age" :min="1" :max="20"></el-input-number>
        </el-form-item>
        <el-form-item label="宠物性别" prop="sex">
          <el-radio-group v-model="newPetForm.sex">
            <el-radio :label="'公'">公</el-radio>
            <el-radio :label="'母'">母</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="领养主人" prop="master">
          <el-input v-model="newPetForm.master"></el-input>
        </el-form-item>
        <el-form-item label="领养状态" prop="state">
          <el-switch v-model="newPetForm.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="描述" prop="desci">
          <el-input type="textarea" v-model="newPetForm.desci"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAddForm = false">取消</el-button>
        <el-button type="primary" @click="submitNewPet">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改宠物的弹出框 -->
    <el-dialog title="修改宠物" :visible.sync="showEditForm" width="30%">
      <el-form :model="editPetForm" ref="editPetFormRef" :rules="rules">
        <el-form-item label="宠物姓名" prop="name">
          <el-input v-model="editPetForm.name"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型">
          <el-select v-model="editPetForm.type" placeholder="请选择宠物类型">
            <el-option label="狗" value="狗"></el-option>
            <el-option label="猫" value="猫"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物年龄" prop="age">
          <el-input-number v-model="editPetForm.age" :min="1" :max="20"></el-input-number>
        </el-form-item>
        <el-form-item label="宠物性别" prop="sex">
          <el-radio-group v-model="editPetForm.sex">
            <el-radio :label="'公'">公</el-radio>
            <el-radio :label="'母'">母</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="领养主人" prop="master">
          <el-input v-model="editPetForm.master"></el-input>
        </el-form-item>
        <el-form-item label="领养状态" prop="state">
          <el-switch v-model="editPetForm.state" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="描述" prop="desci">
          <el-input type="textarea" v-model="editPetForm.desci"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditForm = false">取消</el-button>
        <el-button type="primary" @click="submitEditPet">确定</el-button>
      </span>
    </el-dialog>
  <!--  -->
  <!-- 表格设计部分 -->
  <!--  -->
    <el-table
      :data="dangqianyeData"
      style="width: 100%"
      @row-click="selectRow">
      <el-table-column
        label="宠物id" align='center'  prop="id"
        width="180">
      </el-table-column>
      <el-table-column
        label="宠物姓名" align='center'  prop="name">
      </el-table-column>
      <el-table-column
        label="宠物年龄" align='center'  prop="age">
      </el-table-column>
      <el-table-column
        label="宠物类型" align='center'  prop="type">
      </el-table-column>
      <el-table-column
        label="宠物性别" align='center'  prop="sex">
      </el-table-column>
      <el-table-column
        label="领养主人" align='center'  prop="master">
      </el-table-column>
      <el-table-column
        label="领养状态" align='center'  prop="state">
      </el-table-column>
      <el-table-column
        label="描述" align='center'  prop="desci">
      </el-table-column>
      <el-table-column align='center' label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="showConfirm(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-size="10"
      :pager-count="11"
      layout="prev, pager, next"
      :total="adoptList.length"
      @current-change="changepage"
    ></el-pagination>
    
<!-- 查询结果弹窗 -->
    <el-dialog title="查询结果" :visible.sync="showSearchResults" width="50%">
      <el-table
        :data="searchResultList"
        style="width: 100%">
        <el-table-column
          label="宠物id" align='center'  prop="id"
          width="180">
        </el-table-column>
        <el-table-column
          label="宠物姓名" align='center'  prop="name">
        </el-table-column>
        <el-table-column
          label="宠物年龄" align='center'  prop="age">
        </el-table-column>
        <el-table-column
          label="宠物类型" align='center'  prop="type">
        </el-table-column>
        <el-table-column
          label="宠物性别" align='center'  prop="sex">
        </el-table-column>
        <el-table-column
          label="领养主人" align='center'  prop="master">
        </el-table-column>
        <el-table-column
          label="领养状态" align='center'  prop="state">
        </el-table-column>
        <el-table-column
          label="描述" align='center'  prop="desci">
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Adopt',
  data() {
    return {
      fromData: {
        name: '',
        type: ''
      },
      adoptList: [],
      dangqianpage: 1,
      showAddForm: false,
      showEditForm: false, // 控制修改表单的显示隐藏
      selectedRow: null,
      newPetForm: {
        name: '',
        type: '',
        age: 1,
        sex: '男',
        master: '',
        state: '',
        desci: ''
      },
      editPetForm: {}, // 用于存储要编辑的数据
      rules: {
        name: [{ required: true, message: '请输入宠物姓名', trigger: 'blur' }],
        age: [{ required: true, message: '请输入宠物年龄', trigger: 'change' }],
        sex: [{ required: true, message: '请选择宠物性别', trigger: 'change' }],
        master: [{ required: true, message: '请输入领养主人', trigger: 'blur' }]
      },
      searchResultList: [], // 用于存储查询结果
      showSearchResults: false // 控制查询结果弹窗的显示隐藏
    };
  },
  computed: {
    dangqianyeData() {
      const qishi = (this.dangqianpage - 1) * 10;
      return this.adoptList.slice(qishi, qishi + 10);
    },
    isDataLoaded() {
      return this.adoptList.length > 0;
    }
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get("http://localhost:8081/adoptUser/list")
        .then((response) => {
          this.adoptList = response.data.data;
          this.maxPage = Math.ceil(this.adoptList.length / 10);
          // this.isDataLoaded = true;
        })
        .catch((error) => {
          console.error('There was an error!', error);
        });
    },
    updateStateText(formName) {
    const form = formName === 'newPetForm' ? this.newPetForm : this.editPetForm;
    form.stateText = form.state === 1 ? '已领养' : '未领养';
  },
  // 刷新方法
    refreshTable() {
      this.fetchData(); // 重新获取数据
    },



// 
// 实现查询方法
// 
    onSelect() {
      const { name, type } = this.fromData;
      let params = {};
      if (name) {
        params['name'] = `%${name}%`; // 使用通配符进行模糊匹配
      }
      if (type) {
        params['type'] = type;
      }

      axios.get("http://localhost:8081/adoptUser/query", { params })
        .then((response) => {
          this.searchResultList = response.data.data;
          this.showSearchResults = true; // 显示查询结果弹窗
          this.dangqianpage = 1; // 重置到第一页
          // this.isDataLoaded = true;
        })
        .catch((error) => {
          console.error('There was an error!', error);
        });
    },
    handleEdit(index, row) {
      // 当点击编辑按钮时，填充编辑表单中的数据
      this.editPetForm = Object.assign({}, row); // 复制行数据到编辑表单
      this.showEditForm = true;
    },
    selectRow(row) {
      this.selectedRow = row;
    },
// 
// 实现删除方法
// 
    showConfirm(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(id);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDelete(id) {
      axios.post(`http://localhost:8081/adoptUser/removeById/${id}`)
        .then((response) => {
          const result = response.data;
          if (result.code == 200) {
            this.adoptList = this.adoptList.filter(item => item.id !== id);
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          } else {
            this.$message.error(result.message || '删除失败');
          }
        })
        .catch((error) => {
          if (error.response && error.response.status === 404) {
            this.$message.error('找不到删除接口，请检查后端配置');
          } else {
            console.error('There was an error!', error);
            this.$message.error('删除失败');
          }
        });
    },
    changepage(page) {
      this.dangqianpage = page;
    },
// 
// 实现添加方法
// 
    submitNewPet() {
      this.$refs.newPetFormRef.validate((valid) => {
        if (valid) {
          const addDto = {
            name: this.newPetForm.name,
            age: this.newPetForm.age,
            type: this.newPetForm.type, // 直接使用字符串形式
            sex: this.newPetForm.sex === '公' ? '公' : '母', // 转换为中文
            master: this.newPetForm.master,
            state: this.newPetForm.state === 1 ? '已领养' : '未领养', // 转换为中文
            desci: this.newPetForm.desci
          };

          axios.post("http://localhost:8081/adoptUser/add", addDto)
            .then((response) => {
              this.refreshTable(); // 添加数据后刷新表
              const newPet = response.data;
              this.adoptList.push(newPet);
              this.showAddForm = false;
              this.$message({
                message: '添加成功',
                type: 'success'
              });
            })
            .catch((error) => {
              console.error('There was an error!', error);
              this.$message.error('添加失败');
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
// 
// 实现修改方法
// 
submitEditPet() {
    this.$refs.editPetFormRef.validate((valid) => {
      if (valid) {
        const editDto = {
          id: this.editPetForm.id,
          name: this.editPetForm.name,
          age: this.editPetForm.age,
          type: this.editPetForm.type,
          sex: this.editPetForm.sex === '公' ? '公' : '母', // 转换为中文
          master: this.editPetForm.master,
          state: this.editPetForm.state === 1 ? '已领养' : '未领养', // 使用数字形式的状态值
          desci: this.editPetForm.desci
        };

        axios.post("http://localhost:8081/adoptUser/modifyById", editDto)
        .then((response) => {
          const result = response.data;
          if (result.code === 200 ) {
            // && result.msg === "success"
            // 更新列表中对应的宠物状态
            // 不需要手动更新本地数据，因为我们将调用 refreshTable()
            this.showEditForm = false; // 关闭编辑表单
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.refreshTable(); // 修改数据后刷新表格
          } else {
            this.$message.error(result.msg || '修改失败');
          }
        })
        .catch((error) => {
          console.error('There was an error!', error);
          this.$message.error('修改失败');
        });
    } else {
      console.log('error submit!!');
      return false;
    }
  });
},
  }
};
</script>


<style scoped>
.el-table {
  margin: auto;
  margin-top: 20px;
}
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>